// pages/shopClass/shopClass.js
const app = getApp()
import Api from '../../utils/api';
import util from '../../utils/util';
// var timer;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hideFlag:false,//防止商铺页面跳转回来再次调用广告接口
    timer:null,
    closePhotosAlbumFlag: false, //首次弹出访问相册授权窗口
    id: '', //店铺id
    shopInfo: {}, //店铺基本信息数据
    shopIsColl: false, //查看是否收藏状态
    tabList: ['领红包', '惠买买'], //tab切换列表
    tabListIndex: 0, //tab切换索引值
    tabConTop: 0, //tab元素top
    isflagTab: false, //tab是否固定在顶部
    shopBannerList: [], //店铺的轮播数据
    shopGoodsSort: [], //店铺商品分类数据
    shopGoodsSortIndex: 0, //店铺商品分类索引值
    //model_1 只购买,并排两张小图; model_2 先显示只展示大图再显示可购买两张小图; model_3 先显示海报再显示只购买, 大图显示 
    //model_4 先显示海报再显示只展示, 小图显示; model_5 先显示海报再显示只展示, 大图显示; model_6 纯海报显示
    modelType: '',
    goods: {}, //商品集合
    isCartPopup: false, //是否弹出加入购物车
    num: 1, //购物数量默认为1
    recordList: [], //红包列表数据
    page: 1,
    size: 10,
    isIntr: true,
    bigBackBoolean: false, //整个大的遮罩层的布尔值
    h5Boolean: false, //小的金币的模態框的彈出
    merchantDtoPrice: 0, //是否有钱赚的价格

    isPrize: null, //判断是否是有钱赚码 true为是
    shareViewOpen: false, // 分享框显示标识
    qrcode_temp: '', //小程序码
    huiImg: '/img/hui-img01.png',
    bgImg: "/img/money-img.png",
    showDialog: false, //点击分享朋友圈时，绘制图的标志
    windowWidth: 375,
    windowHeight: 603,
    _productImg: '',
    portrait_temp: '',
    latitude: '', //店铺纬度
    longitude: '', //店铺经度
    shareRecordId: '', //分享记录id
    advertisement: '', //广告信息
    advertisementId: '', //广告id
    countDownNum: 5,
    ty: '',

    imagewidth: '',
    imageheight: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let _this = this;
    console.log(options, '店铺参数')
    //options.id = "1156013043126243328"
    if (options.id != undefined) {
      //console.log(options.id)
      _this.setData({
        id: options.id
      })
      _this.allIndexLoad();
      if (options.ty == "POP") {
        console.log('options.ty==pop:扫码进来的标志')
        _this.setData({
          ty: options.ty,
          shareRecordId: options.shareRecordId
        })

      }
    }

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    if (_this.data.loginFlag) {
      _this.allIndexLoad();
    }
    if (_this.data.ty == 'POP' && !_this.data.hideFlag) {
      var cityFlag = wx.getStorageSync('originalData').addressComponent.city;
      console.log(_this.data.hideFlag, '_this.data.hideFlag')
      // 调广告接口
      _this.popAds(cityFlag);
      app.globalData.indexRequestFlag = false;
      _this.setData({
        hideFlag: false
      })
    }
  },

  // 调广告接口
  popAds: function(cityFlag) {
    var _this = this;
    Api.popAds(cityFlag).then(res => {
      console.log(res.data, '调广告接口success');
      var advertisement = res.data;
      if (advertisement.id) {
        _this.setData({
          advertisement: advertisement,
        })
        //微信用户扫码进入店铺
        _this.intoShop(advertisement.id);
      }
     
    })

  },
  //5秒定时器
  countDown: function() {
    let that = this;
    let countDownNum = 5; //获取倒计时初始值 
    that.setData({
      countDownNum: countDownNum
    })
    that.setData({
    timer : setInterval(function() {
      countDownNum--;
      that.setData({
        countDownNum: countDownNum

      })
      if (countDownNum <= 0) {
        if (that.data.timer){
          clearInterval(that.data.timer);
          // timer = null;
          that.setData({
            timer:null
          })
        }
        that.setData({
          advertisement: '',
          countDownNum: 5,
        })
      }
    }, 1000)
    })
  },
  closeAds: function() {
    var that = this;
    that.setData({
      advertisement: '',
    })
    clearInterval(that.data.timer);
  },
  // 点击广告进入店铺
  joinAds: function (e) {
    var that = this;
    var advertisementId = e.currentTarget.dataset.id;
    var jumpPath = that.data.advertisement.jumpPath;
    console.log(jumpPath, '========跳转路径')
    if (jumpPath) {
      Api.clickAds(advertisementId).then(res => {
        console.log(res, '调点击广告success');
        if (that.data.advertisement.shopId) {
          wx.navigateTo({
            url: jumpPath,
          })
        }
      })
    }
    // else{
    //   Api.clickAds(advertisementId).then(res => {
    //     console.log(res, '调点击广告success');
    //       wx.navigateTo({
    //         url: '/pages/shopClass/shopClass?id=1169503585352945664',
    //       })
    //   })
    // }

  },
  // 扫码进入店铺
  intoShop: function (advertisementId) {
    var that = this;
    Api.intoShop({
      "shareRecordId": that.data.shareRecordId,
      "advertisementId": advertisementId,
    }).then(res => {
      console.log(res, '调扫码进入店铺uccess');
    })
  },

  imageLoad: function(e) {
    // 5秒广告倒计时
    this.countDown();
    var imageSize = util.imageUtil(e)
    this.setData({
      imagewidth: imageSize.imageWidth,
      imageheight: imageSize.imageHeight
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    let _this = this;
    wx.createSelectorQuery().select('#tab_con').boundingClientRect(function(rect) {
      _this.setData({
        tabConTop: rect.top
      })
    }).exec();
    wx.createSelectorQuery().select('.canvas-box').boundingClientRect(function(rect) {
      if (rect.width >= 375) {
        _this.setData({
          windowWidth: 375, // 节点的宽度
          windowHeight: 603 // 节点的高度
        })
      } else {
        _this.setData({
          windowWidth: 320, // 节点的宽度
          windowHeight: 504 // 节点的高度
        })
      }

    }).exec();

    var third_Session = wx.getStorageSync('third_Session');
    if (third_Session) {
      _this.clickMerchantDto(); //点击有钱赚
    }
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    console.log(' 生命周期函数--监听页面隐藏')
    var that = this;
    if (that.data.timer){
      clearInterval(that.data.timer);
      // timer = null;
      that.setData({
        timer:null
      })
    }
    that.setData({
      advertisement: '',
     hideFlag:true
    })

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    //console.log("上拉加载")
    let _this = this;
    if (_this.data.page < _this.data.totalPages) {
      _this.setData({
        page: _this.data.page + 1
      })
      wx.showLoading({
        title: '加载中',
      })
      if (tabListIndex == 0) { //切换到红包
        _this.getShopRecord(function() {
          setTimeout(function() {
            wx.hideLoading()
          }, 1000)
        });
      } else { //切换到惠买买

      }

    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(options) {
    // 分享页面导致小程序进入小程序后台或前台;
    app.globalData.otherPageHideFlag = true;
    console.log('店铺分享===用户点击右上角分享otherPageHideFlag==', app.globalData.otherPageHideFlag)

    console.log(options, '=========店铺')
    var that = this;
    var shareObj = {
      title: that.data.shopInfo.shopName,
      path: 'pages/shopClass/shopClass?id=' + that.data.id + '&title=' + JSON.stringify(that.data.shopInfo.shopName),
    }
    setTimeout(function() {
      that.setData({
        shareViewOpen: false
      })
    }, 2000)
    // 来自页面内的按钮的转发
    // if (options.from == 'button') {
    return shareObj;


  },
  //首次进来需要加载的数据
  allIndexLoad: function() {
    let _this = this;
    _this.getShopInfo(); //店铺基本数据信息
    //查询店铺是否时收藏
    _this.isCollData();
    //查询店铺轮播
    _this.getShopBanner();
    //获取红包liebia
    _this.getShopRecord();

  },
  //预览店铺商标
  preShopImage(e) {
    var current = e.currentTarget.dataset.shopimage;
    console.log('预览店铺商标', current);
    wx.previewImage({
      current: current, // 当前显示图片的http链接  
      urls: [current, this.data.shopInfo.miniCodeImage] // 需要预览的图片http链接列表  
    })
  },
  //店铺基本数据信息
  getShopInfo() {
    let _this = this;
    Api.getShopInfo(_this.data.id).then(res => {
      console.log("店铺基本数据信息", res.data.shop)
      let txMap = util.bMapTransTXmap(res.data.shop.longitude, res.data.shop.latitude);
      _this.setData({
        shopInfo: res.data.shop,
        visitOfMonth: res.data.visitOfMonth,
        visitOfTotal: res.data.visitOfTotal,
        modelType: res.data.modelType,
        latitude: txMap.lat, //店铺纬度
        longitude: txMap.lng, //店铺经度

      })
      // 获取头像到本地 ，做分享绘制图片用（网络图片无法绘制）  
      wx.downloadFile({
        url: _this.data.shopInfo.trademarkImage,
        success(res) {
          if (res.statusCode === 200) {
            //console.log(res)
            let image = res.tempFilePath
            //console.log(image)
            _this.setData({
              portrait_temp: image
            })
          }
        }
      })
      //查询店铺商品分类
      _this.getShopGoodsSort();

    })
  },

  //点击有钱赚
  clickMerchantDto() {
    let _this = this;
    let data = {
      userId: wx.getStorageSync("third_Session").openid,
      userName: wx.getStorageSync("userInfo").nickName,
      shopId: _this.data.id
    }
    console.log(data, 'data')
    Api.clickMerchantDto(data).then(res => {
      console.log("点击有钱赚", res)
      if(res.data){
        if (res.data.data) {
          _this.setData({
            h5Boolean: !_this.data.h5Boolean,
            bigBackBoolean: !_this.data.bigBackBoolean,
            merchantDtoPrice: res.data.data.data,
          });
          // setTimeout(function () {
          //   _this.setData({
          //     h5Boolean: !_this.data.h5Boolean,
          //     bigBackBoolean: !_this.data.bigBackBoolean,
          //     merchantDtoPrice: 0,
          //   });
          // }, 3000);
        }
      }
    });
  },
  // 关闭点击有钱赚
  closeRedPacketBg() {
    var _this = this;
    _this.setData({
      h5Boolean: !_this.data.h5Boolean,
      bigBackBoolean: !_this.data.bigBackBoolean,
    });
  },

  //查询店铺是否时收藏
  isCollData() {
    let _this = this;
    Api.isCollData(_this.data.id).then(res => {
      //console.log(res)
      _this.setData({
        shopIsColl: res.data
      })
    })
  },

  //收藏状态 点击可以取消收藏
  collClick() {
    let _this = this;
    Api.delColl(_this.data.id).then(res => {
      // console.log(res)
      wx.showToast({
        title: '取消收藏',
        icon: 'success',
        duration: 2000
      })
      _this.setData({
        shopIsColl: false,
      })
    })
  },

  //未收藏状态 点击可以收藏
  nocollClick() {
    let _this = this;
    Api.addColl(_this.data.id).then(res => {
      console.log(res)
      wx.showToast({
        title: '收藏成功',
        icon: 'success',
        duration: 2000
      })
      _this.setData({
        shopIsColl: true,
      })
    })
  },

  //tab切换事件
  changeTab(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    _this.setData({
      tabListIndex: index,
    });

  },

  //页面滚动 tab固定位置
  bindscroll(e) {
    let _this = this;
    let top = e.detail.scrollTop;
    //console.log(top)
    if (_this.data.tabConTop < top) {
      _this.setData({
        isflagTab: true
      })
    } else {
      _this.setData({
        isflagTab: false
      })
    }
  },

  //查询店铺轮播
  getShopBanner() {
    let _this = this;
    Api.getShopBanner(_this.data.id).then(res => {
      console.log("查询店铺轮播", res)
      _this.setData({
        shopBannerList: res.data
      })


    })
  },

  //查询店铺商品分类
  getShopGoodsSort() {
    let _this = this;
    Api.getShopGoodsSort(_this.data.id).then(res => {
      console.log(res.data, '查询店铺商品分类')
      if (res.data.length > 0) {
        _this.setData({
          shopGoodsSort: res.data
        })
        //获取店铺分类商品数据
        _this.getGoodsList();
      }
    })
  },

  //店铺商品分类数据切换
  shopGoodsSortClick(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    _this.setData({
      shopGoodsSortIndex: index
    })
    //获取店铺分类商品数据
    _this.getGoodsList();
  },

  //获取店铺分类商品数据
  getGoodsList() {
    let _this = this;
    //console.log(_this.data.modelType)
    //type 商品类型 (SHOW:仅展示 BUY:购买 POSTER:海报)
    if (_this.data.modelType == "model_1") {
      _this.getGoodsListType("BUY");
    } else if (_this.data.modelType == "model_2") {
      _this.getGoodsListType("SHOW");
      _this.getGoodsListType("BUY");
    } else if (_this.data.modelType == "model_3") {
      _this.getGoodsListType("POSTER");
      _this.getGoodsListType("BUY");
    } else if (_this.data.modelType == "model_4") {
      _this.getGoodsListType("POSTER");
      _this.getGoodsListType("SHOW");
    } else if (_this.data.modelType == "model_5") {
      _this.getGoodsListType("POSTER");
      _this.getGoodsListType("SHOW");
    } else if (_this.data.modelType == "model_6") {
      _this.getGoodsListType("POSTER");
    }
  },
  //获取店铺分类商品数据 //type 商品类型 (SHOW:仅展示 BUY:购买 POSTER:海报)
  getGoodsListType(type) {
    //model_1 只购买,并排两张小图; model_2 先显示只展示大图再显示可购买两张小图; model_3 先显示海报再显示大图购买,
    //model_4 先显示海报再显示小图展示; model_5 先显示海报再显示大图展示; model_6 纯海报显示

    let _this = this;
    //console.log(_this.data.shopGoodsSort[_this.data.shopGoodsSortIndex].id)
    Api.getGoodsList(_this.data.shopGoodsSort[_this.data.shopGoodsSortIndex].id, type).then(res => {
      //console.log(res)
      let dataName = 'goods.' + type + '';
      //console.log(dataName)
      _this.setData({
        [dataName]: res.data,
      });
      //console.log(_this.data.goods);
    })
  },

  //展示加入购物车弹出框
  showCart(e) {
    let _this = this;
    let info = e.currentTarget.dataset.info;
    _this.setData({
      isCartPopup: true,
      goodsDetailInfo: info
    })
  },
  //关闭加入购物车弹出框
  colseCart() {
    let _this = this;
    _this.setData({
      isCartPopup: false,
    })
  },

  //减少数量
  subNum() {
    let _this = this;
    if (_this.data.num > 1) {
      _this.setData({
        num: _this.data.num - 1
      })
    }
  },
  //添加数量
  addNum() {
    let _this = this;
    _this.setData({
      num: _this.data.num + 1
    })
  },

  //加入购物车接口

  addCart() {
    let _this = this
    Api.addCart(_this.data.goodsDetailInfo.id, _this.data.num).then(res => {
      //console.log("加入购物车接口",res)
      wx.showToast({
        title: '添加成功',
        icon: 'success',
        duration: 2000
      })
      _this.setData({
        isCartPopup: false,
      })
      app.loadCartNum();
    })
  },

  //获取红包列表
  getShopRecord(callback) {
    let _this = this;
    let data = {
      "shopId": _this.data.id,
    }
    console.log(data)
    Api.getShopRecord(data, _this.data.page, _this.data.size).then(res => {
      console.log(res)
      _this.setData({
        recordList: _this.data.recordList.concat(res.data.dataList)
      });
      _this.data.recordList.forEach(function(item, index, arr) {
        if (item.activiteStartTime) {
          item.activiteStartTime = util.formatTime(new Date(item.activiteStartTime))
        }
        if (item.activiteEndTime) {
          item.activiteEndTime = util.formatTime(new Date(item.activiteEndTime))
        }
        item.expireTime = util.formatTime(new Date(item.expireTime))
        _this.setData({
          recordList: arr
        })
      });
      (callback && typeof(callback) === "function") && callback();
    })
  },

  //领取红包
  getPrice(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;

    Api.getPrice(_this.data.recordList[index].id).then(res => {
      console.log(res)
      wx.showToast({
        title: '领取成功',
        icon: 'success',
        duration: 2000,
      })
      _this.setData({
        page: 1,
        recordList: [],
      });
      // setTimeout(() => {
      //   _this.setData({
      //     h5Boolean: !_this.data.h5Boolean,
      //     bigBackBoolean: !_this.data.bigBackBoolean
      //   });
      // }, 1500);
      _this.getShopRecord();
    })
  },
  //获取店铺的小程序码
  shopCode(callback) {
    let _this = this;
    Api.shopCode(_this.data.id).then(res => {
      console.log("获取店铺的小程序码", res);
      _this.setData({
        isPrize: res.data.isPrize,

      })
      wx.downloadFile({
        url: res.data.miniCode,
        success(res) {
          if (res.statusCode === 200) {
            //console.log(res)
            let image = res.tempFilePath
            console.log(image)
            _this.setData({
              qrcode_temp: image,
            });
            (callback && (typeof callback) === 'function') && callback();
          }
        }
      })
    })
  },

  /**
   * 点击分享
   */
  share: function() {
    var _this = this;
    _this.setData({
      shareViewOpen: !_this.data.shareViewOpen,
    })
  },

  /**
   * 分享事件
   */
  shareImage(event) {
    var _this = this;
    wx.showLoading({
      title: '加载中',
    })
    //下载商品图片到本地（网络图片canvas无法绘制）
    wx.downloadFile({
      url: _this.data.shopBannerList[0].image,
      success: (res) => {
        console.log("getShopBanner", res);
        _this.setData({
          _productImg: res.tempFilePath
        });
        //获取店铺小程序码
        _this.shopCode(function() {
          wx.hideLoading()
          if (_this.data.portrait_temp == "" || _this.data._productImg == "") {
            return;
          }
          _this.setData({
            shareViewOpen: !_this.data.shareViewOpen
          })
          //缓存canvas绘制小程序二维码
          if (_this.data.isPrize) {
            _this.drawImageMomey(); //有钱赚
          } else {
            _this.drawImage(); //没钱赚
          }
          setTimeout(function() {
            _this.canvasToImage()
          }, 200)
        });
      },
    });


    //console.log(_this.data.productCarousel)
  },
  drawImage() {
    var _this = this;
    var qrPath = _this.data.qrcode_temp;
    let _productImg = _this.data._productImg;
    let portrait_temp = _this.data.portrait_temp;
    console.log(_productImg)
    //console.log(portrait_temp)
    let huiImg = _this.data.huiImg
    var w = _this.data.windowWidth
    var h = _this.data.windowHeight
    //绘制canvas图片    
    const ctx = wx.createCanvasContext('myCanvas')
    if (w < 375) {
      //绘制背景图片
      ctx.setFillStyle('white');
      ctx.save()
      ctx.beginPath()
      ctx.fillRect(0, 0, _this.data.windowWidth, _this.data.windowHeight);
      ctx.arc(50, 35, 25, 0, 2 * Math.PI)
      ctx.fill()
      ctx.clip()
      ctx.drawImage(portrait_temp, 25, 10, 50, 50)
      ctx.restore()
      // 生成店铺名字
      ctx.setFillStyle('#999999')
      ctx.setFontSize(12)
      ctx.setTextAlign('left')
      var _spName = _this.data.shopInfo.shopName;
      if (_spName.length > 15) {
        _spName = _spName.substring(0, 15);
        _spName += '...';
        console.log(_spName)
      }
      ctx.fillText(_spName, 100, 22)
      // // 文字
      ctx.setFillStyle('#000000')
      ctx.setFontSize(14)
      ctx.setTextAlign('left')
      ctx.fillText('发现一家好店铺 ，你也来看看', 100, 50)

      //生成商品图片
      ctx.drawImage(_productImg, 25, 80, 270, 140)


      // //绘制二维码
      ctx.drawImage(qrPath, 110, 240, 100, 100)
      // //点击识别查看商品
      ctx.setFillStyle('#999999')
      ctx.setFontSize(15)
      ctx.setTextAlign('center')
      ctx.fillText('长按识别小程序码进入店铺', 320 / 2, 370)
      //生成惠生活图片
      ctx.drawImage(huiImg, 0, 410, 320, 40)

      ctx.setFillStyle('#999999')
      ctx.setFontSize(10)
      ctx.setTextAlign('center')
      ctx.fillText('本地实体店打折、促销、新品、爆品一网打尽', 320 / 2, 470)
      ctx.draw();
      return;
    }
    //绘制背景图片
    //ctx.setStrokeStyle('#fff')
    ctx.setFillStyle('white');
    ctx.save()
    ctx.beginPath()
    ctx.fillRect(0, 0, _this.data.windowWidth, _this.data.windowHeight);
    ctx.arc(50, 35, 25, 0, 2 * Math.PI)
    ctx.fill()
    ctx.clip()
    ctx.drawImage(portrait_temp, 25, 10, 50, 50)
    ctx.restore()
    // //生成店铺名字
    ctx.setFillStyle('#999999')
    ctx.setFontSize(12)
    ctx.setTextAlign('left')
    var _spName = _this.data.shopInfo.shopName;
    if (_spName.length > 18) {
      _spName = _spName.substring(0, 18);
      _spName += '...';
      console.log(_spName)
    }
    ctx.fillText(_spName, 100, 22)
    // // 文字
    ctx.setFillStyle('#000000')
    ctx.setFontSize(16)
    ctx.setTextAlign('left')
    ctx.fillText('发现一家好店铺 ，你也来看看', 100, 50)

    //生成商品图片
    ctx.drawImage(_productImg, 25, 80, 327.5, 161)


    // //绘制二维码
    ctx.drawImage(qrPath, 120, 260, 130, 130)
    // //点击识别查看商品
    ctx.setFillStyle('#999999')
    ctx.setFontSize(15)
    ctx.setTextAlign('center')
    ctx.fillText('长按识别小程序码进入店铺', 375 / 2, 430)
    //生成惠生活图片
    ctx.drawImage(huiImg, 0, 480, 375, 40)

    ctx.setFillStyle('#999999')
    ctx.setFontSize(10)
    ctx.setTextAlign('center')
    ctx.fillText('本地实体店打折、促销、新品、爆品一网打尽', 375 / 2, 550)
    ctx.draw();

  },

  drawImageMomey() {
    var _this = this;
    var qrPath = _this.data.qrcode_temp;
    let _productImg = _this.data._productImg;
    let portrait_temp = _this.data.portrait_temp;
    console.log(_productImg)
    //console.log(portrait_temp)
    let huiImg = _this.data.huiImg
    var w = _this.data.windowWidth
    var h = _this.data.windowHeight
    //绘制canvas图片    
    const ctx = wx.createCanvasContext('myCanvas')
    if (w < 375) {
      //绘制背景图片
      ctx.drawImage(_this.data.bgImg, 0, 0, w, h)
      ctx.save()
      ctx.setFillStyle('white');
      ctx.save()
      ctx.beginPath()
      ctx.fillRect(10, 70, 300, 320);
      ctx.arc(60, 105, 20, 0, 2 * Math.PI)
      ctx.fill()
      ctx.clip()
      ctx.drawImage(portrait_temp, 40, 85, 40, 40)
      ctx.restore()
      // //生成店铺名字
      ctx.setFillStyle('#999999')
      ctx.setFontSize(12)
      ctx.setTextAlign('left')
      var _spName = _this.data.shopInfo.shopName;
      if (_spName.length > 15) {
        _spName = _spName.substring(0, 15);
        _spName += '...';
        console.log(_spName)
      }
      ctx.fillText(_spName, 90, 100)
      // // 文字
      ctx.setFillStyle('#000000')
      ctx.setFontSize(14)
      ctx.setTextAlign('left')
      ctx.fillText('发现一家好店铺 ，你也来看看', 90, 122)

      //生成商品图片
      ctx.drawImage(_productImg, 40, 160, 230, 120)

      // //绘制二维码
      ctx.drawImage(qrPath, 125, 290, 60, 60)
      // //点击识别查看商品
      ctx.setFillStyle('#999999')
      ctx.setFontSize(12)
      ctx.setTextAlign('center')
      ctx.fillText('长按识别小程序码进入店铺', 300 / 2, 370)
      ctx.draw();
      return;
    }
    //绘制背景图片
    //ctx.setStrokeStyle('#fff')
    ctx.drawImage(_this.data.bgImg, 0, 0, w, h)
    ctx.save()
    ctx.setFillStyle('white');
    ctx.save()
    ctx.beginPath()
    ctx.fillRect(22, 79, _this.data.windowWidth - 46, 390);
    ctx.arc(59, 114, 25, 0, 2 * Math.PI)
    ctx.fill()
    ctx.clip()
    ctx.drawImage(portrait_temp, 34, 89, 50, 50)
    ctx.restore()
    // //生成店铺名字
    ctx.setFillStyle('#999999')
    ctx.setFontSize(12)
    ctx.setTextAlign('left')
    var _spName=  _this.data.shopInfo.shopName;
    if (_spName.length > 18) {
      _spName = _spName.substring(0, 18);
      _spName += '...';
      console.log(_spName)
    }
    ctx.fillText(_spName, 100, 105)
    // // 文字
    ctx.setFillStyle('#000000')
    ctx.setFontSize(14)
    ctx.setTextAlign('left')
    ctx.fillText('发现一家好店铺 ，你也来看看', 100, 130)

    //生成商品图片
    ctx.drawImage(_productImg, 34, 150, 306, 150)


    // //绘制二维码
    console.log(qrPath)
    ctx.drawImage(qrPath, 135, 320, 100, 100)
    // //点击识别查看商品
    ctx.setFillStyle('#999999')
    ctx.setFontSize(15)
    ctx.setTextAlign('center')
    ctx.fillText('长按识别小程序码进入店铺', 375 / 2, 450)
    //生成惠生活图片
    // ctx.drawImage(huiImg, 0, 480, 375, 40)

    // ctx.setFillStyle('#999999')
    // ctx.setFontSize(10)
    // ctx.setTextAlign('center')
    // ctx.fillText('本地实体店打折、促销、新品、爆品一网打尽', 375 / 2, 550)

    ctx.draw();

  },

  canvasToImage() {
    var _this = this
    console.log()
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: _this.data.windowWidth * 2,
      height: _this.data.windowHeight * 2,
      destWidth: _this.data.windowWidth * 2,
      destHeight: _this.data.windowHeight * 2,
      canvasId: 'myCanvas',
      success: function(res) {
        console.log('朋友圈分享图生成成功:' + res.tempFilePath)
        _this.setData({
          shareImgSrc: res.tempFilePath,
          showDialog: true,
        })
        // wx.previewImage({
        //   current: 'www.ooago.com', // 当前显示图片的http链接
        //   urls: [res.tempFilePath] // 需要预览的图片http链接列表
        // })
      },
      fail: function(err) {
        console.log('失败')
        console.log(err)
      }

    })
  },

  //关闭弹出框
  colseClick() {
    let _this = this;
    // _this.setData({
    //   showDialog: false
    // })
  },
  //长按保存图片
  /**
   * 保存图片
   */
  save: function() {
    //wx.saveImageToPhotosAlbum将图片保存到本地  3
    var _this = this;
    wx.saveImageToPhotosAlbum({
      filePath: _this.data.shareImgSrc,
      success(res) {
        console.log(111)
        wx.hideLoading();
        wx.showModal({
          title: '存图成功',
          content: '图片成功保存到相册了，去发朋友圈噻~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function(res) {
            if (res.confirm) {
              _this.setData({
                showDialog: false
              })
              console.log('用户点击确定');
            }
          }
        })
      },
      fail(err) {
        console.log(err, _this.data.closePhotosAlbumFlag, '_this.data.closePhotosAlbumFlag')
        // 用户点击授权访问相册的取消按钮
        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          console.log('saveImageToPhotosAlbum：失败函数')
          if (_this.data.closePhotosAlbumFlag) {
            wx.showModal({
              title: '您已限制访问相册',
              content: '是否重新授权？',
              success: function(res) {
                if (res.confirm) {
                  wx.openSetting({
                    success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                        console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                        wx.showToast({
                          title: '获取权限成功',
                          icon: 'success',
                          duration: 2000,
                        })
                      } else {
                        console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                        wx.showToast({
                          title: '获取权限失败！',
                          icon: 'none',
                          duration: 2000,

                        })
                      }
                    },
                    fail(error) {
                      console.log(error)
                    }

                  })
                } else if (res.cancel) {
                  wx.showToast({
                    title: '已取消重新授权',
                    icon: 'none'
                  })
                  return
                }
              }
            })
          } else {
            console.log('用户点击授权访问相册的取消按钮')
          }
          _this.setData({
            closePhotosAlbumFlag: true
          })

        }
      }
    })
  },


  isIntrClick() {
    let _this = this;
    _this.setData({
      isIntr: !_this.data.isIntr,
    })
  },
  // 关闭分享到盆友圈页面事件
  closeShare: function() {
    this.setData({
      showDialog: false
    })
  },
  // 点击地址跳转到地图
  jumpToMap: function() {
    var that = this;
    var addressInfo = that.data.shopInfo.city + that.data.shopInfo.town + that.data.shopInfo.addressDetail
    // { { shopInfo.city } } { { shopInfo.town } } { { shopInfo.addressDetail } }
    console.log(addressInfo, that.data.shopInfo.latitude, that.data.shopInfo.longitude, '====================')
    wx.getLocation({
      type: 'wgs84',
      success: function(res) {
        wx.openLocation({ //​使用微信内置地图查看位置。
          latitude: that.data.latitude, //要去的纬度-地址
          longitude: that.data.longitude, //要去的经度-地址
          name: addressInfo,
          address: addressInfo
        })
      }
    })
  },
  jumpToWallet: function() {
    var that = this;
    wx.navigateTo({
      url: '/pages/wallet/wallet',
    })
    that.closeRedPacketBg();
  },
  // 打电话
  callPhone:function(e){
    var that=this;
    wx.makePhoneCall({
      phoneNumber: that.data.shopInfo.contact,
    })
  }

})